package com.kaluli.project.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJacksonJsonView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kaluli.project.domain.entity.KllMainOrder;
import com.kaluli.project.domain.entity.KllOrderSynApi;
import com.kaluli.project.domain.entity.KllProductVo;
import com.kaluli.project.domain.entity.LipinkaVO;
import com.kaluli.project.domain.repository.KllMainOrderRepository;
import com.kaluli.project.domain.repository.KllOrderSynApiRepository;
import com.kaluli.project.service.KllLipinkaService;
import com.kaluli.project.service.KllMainOrderService;
import com.kaluli.project.service.KllOrderSynApiService;
import com.kaluli.project.service.KllProductService;
import com.kaluli.project.utils.MD5Utils;
import com.kaluli.project.utils.RandomNumber;
import com.kaluli.project.utils.RegexUtil;
import com.kaluli.project.utils.nanshaxml.XmlFanli;

/**
 * 
 * 外部接口
 * 
 * @author niwei
 * 
 */
@Controller
@PropertySource({ "classpath:config.properties","classpath:thridsystem.properties" })
public class SynApiController {

	private static Logger log = Logger.getLogger(SynApiController.class);

	@Autowired
	private Environment env;

	@Autowired
	private KllOrderSynApiService kllOrderSynApiService;
	
	@Autowired
	private KllMainOrderRepository kllMainOrderRepository;

	@Autowired
	private KllOrderSynApiRepository kllOrderSynApiRepository;

	@Autowired
	private KllMainOrderService kllMainOrderService;
	
	@Autowired
	private KllLipinkaService kllLipinkaService;

	@RequestMapping(value = "/synApi/findOrderSynApi")
	@ResponseBody
	public void findOrderSynApi(@RequestParam(value = "orderNumber", required = true) String orderNumber) {

	}

	@RequestMapping(value = "/synApi/updateOrderSynApi")
	@ResponseBody
	public ModelAndView updateOrderSynApi(@RequestParam(value = "orderNumber", required = true) String orderNumber) {

		Map<String, Object> map = new HashMap<>();
		// String str="";
		try {
			map = kllOrderSynApiService.updateSynApiStatus(orderNumber);
		} catch (Exception e) {
			map.put("code", 0);
			map.put("message", "更新失败失败!");
			// str=JSON.toJSONString(map);
		}
		return new ModelAndView(new MappingJacksonJsonView(), map);

	}
	
	@RequestMapping(value = "/synApi/sendNr", method = RequestMethod.POST)
	@ResponseBody
	public void sendNrBypostMain(@RequestParam(value = "orderNumber", required = true) String orderNumber){
		SimpleDateFormat sFormat = new SimpleDateFormat("YYYYMMddHHmmss");
		String msgId = sFormat.format(new Date())+RandomNumber.getRandom();
		kllMainOrderService.sendXml(orderNumber, "EDI", msgId);
		
	}

	/**
	 * EDI消息重推
	 * @param orderNumber
	 * @return
	 */
	@RequestMapping(value = "/synApi/updateSendNr")
	@ResponseBody
	public ModelAndView updateSendNr(@RequestParam(value = "orderNumber", required = true) String orderNumber) {

		Map<String, Object> map = new HashMap<>();
		log.info("/synApi/updateSendNr%%orderNumber="+orderNumber);
		// String str="";
		try {
			map = kllOrderSynApiService.updateSendNr(orderNumber);
		} catch (Exception e) {
			map.put("code", 0);
			map.put("message", "更新失败失败!");
			// str=JSON.toJSONString(map);
		}
		return new ModelAndView(new MappingJacksonJsonView(), map);

	}

	/**
	 *  EDI取消订单
	 * @param orderNumber
	 * @return
	 */
	@RequestMapping(value = "/synApi/cancelSendNr", method = RequestMethod.POST)
	@ResponseBody
	public ModelAndView cancelSendNr(@RequestParam(value = "orderNumber", required = true) String orderNumber) {
		Map<String, Object> map = new HashMap<>();
		log.info("/synApi/cancelSendNr&&&orderNumber="+orderNumber);
		String code = "";
		String message = "";
		try {
			KllOrderSynApi api = kllOrderSynApiRepository.findByOrderNumber(orderNumber);
			if (api != null) {
				if (api.getSendNr() == 5) {

					map.put("code", "2");
					map.put("message", "推送能容成功,不能取消订单!");
					return new ModelAndView(new MappingJacksonJsonView(), map);
				}
				if (api.getSendNr() == 4) {

					map.put("code", "4");
					map.put("message", "订单已经取消!");
					return new ModelAndView(new MappingJacksonJsonView(), map);
				}
				if (api.getSendNr() == 2) {
							
					map.put("code", "2");
					map.put("message", "订单已经推送成功,不能进行取消");
					return new ModelAndView(new MappingJacksonJsonView(), map);
				}
				
				if(api.getSendNr() == 0 || api.getSendNr() == 3 || api.getSendNr() == 6){
					//直接取消
					String username = env.getProperty("user.name.nb");
					kllMainOrderService.cancelResult(api.getOrderNumber(), username);
					
					code = "0";
					message = "取消成功!";
					return new ModelAndView(new MappingJacksonJsonView(), map);
				}

				kllMainOrderService.cancelEDIOrder(api);
				
				code = "0";
				message = "取消成功!";
			} else {
				KllMainOrder mainOrder = kllMainOrderRepository.findByOrderNumber(orderNumber);
				if(mainOrder !=null){
					//直接取消
					String username = env.getProperty("user.name.nb");
					kllMainOrderService.cancelResult(api.getOrderNumber(), username);
					kllMainOrderRepository.updateOrderSynApi(mainOrder.getOrderNumber());
					code = "0";
					message = "取消成功!";
				}else{
					code = "1";
					message = "查询不到该订单!";
				}
				
			}
		} catch (Exception e) {
			code = "3";
			message = e.getMessage();
		}
		map.put("code", code);
		map.put("message", message);
		return new ModelAndView(new MappingJacksonJsonView(), map);

	}
	
	
	/**
	 * EDI订单取消回执处理
	 * @param orderNo
	 * @param result
	 * @param res
	 */
	@RequestMapping(value = "/synApi/cancelEDIorder")
	public void cancelEDIorder(@RequestParam(value = "orderNo", required = true) String orderNo,
			@RequestParam(value = "result", required = true) String result,HttpServletResponse res) {
		Map<String, Object> map = new HashMap<>();
		log.info("cancelEDIorder.orderNo="+orderNo+"&&&result="+result);
		try {
			if (result.equals("success")) {
				// 更新推送池状态
				kllOrderSynApiService.cancelEDIResult(orderNo);
			}

		} catch (Exception e) {
			
		}
		
		try {
			PrintWriter out = res.getWriter();
			out.print("success");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	
	/**
	 *  EDI取消订单 异常情况下手动取消
	 * @param orderNumber
	 * @return
	 */
	@RequestMapping(value = "/synApi/cancelNrtest", method = RequestMethod.POST)
	@ResponseBody
	public ModelAndView cancelNrtest(@RequestParam(value = "orderNumber", required = true) String orderNumber) {
		Map<String, Object> map = new HashMap<>();
		log.info("/synApi/cancelSendNr&&&orderNumber="+orderNumber);
		String code = "";
		String message = "";
		try {
			KllOrderSynApi api = kllOrderSynApiRepository.findByOrderNumber(orderNumber);
			if (api != null) {

				kllMainOrderService.cancelEDIOrder(api);
				
				code = "0";
				message = "取消成功!";
			} else {
				code = "1";
				message = "api订单数据为空!";
			}
		} catch (Exception e) {
			code = "3";
			message = e.getMessage();
		}
		map.put("code", code);
		map.put("message", message);
		return new ModelAndView(new MappingJacksonJsonView(), map);

	}
	

	@RequestMapping(value = "/order/cancelOrder")
	@ResponseBody
	public ModelAndView cancelOrder(@RequestParam(value = "orderNumber", required = true) String orderNumber) {
		Map<String, Object> map = new HashMap<>();
		log.info("/order/cancelOrder%%orderNumber="+orderNumber);
		String code = "";
		String message = "";
		try {
			KllOrderSynApi api = kllOrderSynApiRepository.findByOrderNumber(orderNumber);
			if (api != null) {
				if (api.getSendZz() == 2) {

					map.put("code", "2");
					map.put("message", "推送卓志成功,不能取消订单!");
					return new ModelAndView(new MappingJacksonJsonView(), map);
				}
				if (api.getSendZz() == 4) {

					map.put("code", "4");
					map.put("message", "订单已经取消!");
					return new ModelAndView(new MappingJacksonJsonView(), map);
				}

				kllMainOrderService.cancelResult(orderNumber,env.getProperty("user.name.ns"));
				code = "0";
				message = "取消成功!";
			} else {
				code = "1";
				message = "查询不到该订单!";
			}
		} catch (Exception e) {
			code = "3";
			message = e.getMessage();
		}
		map.put("code", code);
		map.put("message", message);
		return new ModelAndView(new MappingJacksonJsonView(), map);
	}
	
	@RequestMapping(value = "/order/lipinka")
	@ResponseBody
	public ModelAndView findLipinka(@RequestParam(value = "orderNumber", required = true) String orderNumber) {
		Map<String, Object> map = new HashMap<>();
		log.info("/order/lipinka%%orderNumber="+orderNumber);
		String code = "";
		String message = "";
		LipinkaVO vo = null;
		try {
			vo = kllLipinkaService.findLipinka(orderNumber);
			if (vo != null) {
				
				code = "0";
				message = "";
			} else {
				code = "1";
				message = "查询不到优惠券!";
			}
		} catch (Exception e) {
			code = "3";
			message = e.getMessage();
		}
		map.put("code", code);
		if(vo == null){
			map.put("data", "{}");
		}else{
			map.put("data", JSON.toJSONString(vo));
		}
		map.put("message", message);
		return new ModelAndView(new MappingJacksonJsonView(), map);
	}
	
	public static void main(String[] args) {
		LipinkaVO vo = new LipinkaVO();
		vo.setApply("123");
		vo.setCardLimit("300");
		vo.setForWhat("xxxx");
		System.out.println(JSON.toJSONString(vo));
	}

	
}
